package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.LitemallCommissionLogMapper;
import org.linlinjava.litemall.db.dao.LitemallCommissionMapper;
import org.linlinjava.litemall.db.domain.LitemallCommission;
import org.linlinjava.litemall.db.domain.LitemallCommissionApply;
import org.linlinjava.litemall.db.domain.LitemallCommissionLog;
import org.linlinjava.litemall.db.domain.LitemallOrderCommission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户佣金
 */
@Component
public class LitemallCommissionService {
    @Autowired
    private LitemallCommissionMapper commissionMapper;
    @Autowired
    private LitemallCommissionLogMapper commissionLogMapper;

    public List<LitemallCommission> querySelective(Integer userId, String username, Integer page, Integer limit, String sort, String order) {
        LitemallCommission commission = new LitemallCommission();
        commission.setUserId(userId);
        commission.setUsername(username);
        PageHelper.startPage(page, limit);
        return commissionMapper.queryCommissionList(commission, sort, order);
    }

    public LitemallCommission queryByUserId(Integer userId) {
        return commissionMapper.queryByUserId(userId);
    }

    public void saveCommission(LitemallCommission commission) {
        commissionMapper.saveCommission(commission);
    }

    public void updateCommission(LitemallCommission commission, LitemallOrderCommission orderCommission, LitemallCommissionApply apply) {
        //用户佣金变更
        int result = commissionMapper.updateCommission(commission);
        if(result > 0) {
            //佣金变动日志记录
            LitemallCommissionLog log = new LitemallCommissionLog();
            log.setUserId(commission.getUserId());
            log.setCreatedTime(LocalDateTime.now());
            //佣金收益
            if(orderCommission != null) {
                log.setOrderCommissionId(orderCommission.getId());
                log.setCommission(orderCommission.getCommissionPrice());
                log.setFromUid(orderCommission.getUserId());
                log.setType("0");
            }
            //佣金提现
            if(apply != null) {
                log.setApplyId(apply.getId());
                log.setCommission(apply.getCommission());
                log.setType("1");
            }
            commissionLogMapper.save(log);
        }
    }
}
